package com.qingzhu.component.lock.common.config.enums;

import com.qingzhu.component.lock.common.exception.LockConfigException;
import com.qingzhu.component.lock.common.util.BaseUtil;

import java.util.Map;

/**
 * zookeeper的默认配置枚举类
 * @author xiangjz
 * @version 1.0
 * @date 2021/1/20 10:10
 */
public enum ZookeeperEnumConfig {

    /**
     * zkServer的连接地址
     */
    CONNECTION_URL ("connectionUrl", "", false),

    /**
     * 锁位于zkServer上的根节点
     */
    ROOT_PATH ("rootPath", "businessLocks", true),

    /**
     * 锁根节点的失效时间(当到达这个时间没有任何的modify操作，且没有任何子节点时，zk会清除该节点)
     */
    ROOT_PATH_TTL ("rootPathTtl", 24 * 60 * 60 * 1000L, true),
    ;

    private String key; // 配置的key
    private Object value; // 配置的value
    private boolean nullable; // 是否可以为空

    ZookeeperEnumConfig(String key, Object value, boolean nullable) {
        this.key = key;
        this.value = value;
        this.nullable = nullable;
    }

    public String getKey() {
        return key;
    }

    public Object getValue() {
        return value;
    }

    public boolean isNullable() {
        return nullable;
    }

    public static Object getOrDefault(Map config, ZookeeperEnumConfig defaultConfig) {
        if(BaseUtil.isEmpty(config)) {
            throw new LockConfigException("zookeeperConfig is invalid, please make sure that config [zookeeper] exist below root config [lock]");
        }

        if(BaseUtil.isEmpty(config.get(defaultConfig.getKey()))) {
            if(!defaultConfig.isNullable()) {
                throw new LockConfigException("zookeeperConfig is invalid, please make sure that config [zookeeper."+defaultConfig.getKey()+"] exist below config [lock.zookeeper]");
            }
            return defaultConfig.getValue();
        }

        return config.get(defaultConfig.getKey());
    }

}
